package com.dqp.cslggroup;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewStub;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.dqp.cslggroup.Api.jwxtApi;
import com.dqp.cslggroup.Api.xxmhApi;
import com.dqp.cslggroup.EventBus.MessageEvent;
import com.dqp.cslggroup.UI.*;
import com.dqp.cslggroup.Util.*;
import com.dqp.cslggroup.bean.academic;
import com.dqp.cslggroup.bean.avatar;
import com.dqp.cslggroup.bean.event;
import com.dqp.cslggroup.bean.student;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import pub.devrel.easypermissions.EasyPermissions;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class newStudent extends BaseActivity {
    Button xxmh;
    Button jwxt;
    Map<String, String> cookies = new HashMap<>();
    private ViewStub viewstub_loading, viewstub_loading1;
    ExecutorService threadPool = Executors.newFixedThreadPool(5);
    int loginError = 0;
    String xxmhHelp = "https://www.cslggroup.top/ical/xxmhhelp.html";
    boolean bindJwxt = false;
    boolean bind = false;
    boolean xxmhLogined = false;
    static String[] permissions = {
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_CALENDAR,
            Manifest.permission.WRITE_CALENDAR,
            Manifest.permission.READ_EXTERNAL_STORAGE
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.new_student);
        EventBus.getDefault().register(this);
        initCmp();
        showYs();
    }

    public void initCmp() {
        viewstub_loading = findViewById(R.id.viewstub_loading);
        viewstub_loading1 = findViewById(R.id.viewstub_loading1);
        TextView xxmh = findViewById(R.id.xxmh_tip);
        TextView jwxt = findViewById(R.id.jwxt_tip);
        TextView ical = findViewById(R.id.ical_tip);
        xxmh.setText("\t\t绑定该账户用于获取学生校园卡消费、课表、成绩、图书借阅等信息，以及认证教务系统，获取应用完整功能必须完成账号绑定。" +
                "连续超多3️⃣次登录失败，账号将会被限制登录5分钟❗❗请认真确认密码的正确性❗❗忘记密码请查看如下教程❗❗\n" +
                "【系统官网】🔗https://webvpn.cslg.edu.cn\n" +
                "【忘记密码】🔗https://www.cslggroup.top/ical/xxmhhelp.html");
        jwxt.setText("\t\t绑定该账户用于获取学生课表、成绩、考场、等级考试等数据，该账户可以通过信息门户统一身份认证登录，无需再次输入教务系统账户密码登录。\n");
        ical.setText("\t\t将课程信息直接写入日历📅，无需第三方应用支持📵，生成上课日程提醒🔔，支持Android、iPhone、PC，功能获取地址：\n" +
                "🔗https://www.cslggroup.top/ical\n" +
                "🔗https://dqp2375.gitee.io/imk/ical\n");
    }


    public void xxmhLogin() {
        xxmh = findViewById(R.id.bind_xxmh);
        xxmh.setOnClickListener(v -> {
            if (bind) return;
            DialogView.loginDialog(this, "信息门户", (dialog, userid, pwd, checkBox) -> {
                if (loginError >= 3) {
                    EventBus.getDefault().post(new MessageEvent("newStudent", 10, 300000, "信息门户"));
                    return;
                }
                threadPool.execute(() -> {
                    String remberMe = "0";
                    if (checkBox.isChecked()) remberMe = "1";
                    String sno = StringUtil.rmBadParame(userid.getText().toString());
                    String password = StringUtil.rmBadParame(pwd.getText().toString());
                    if (!StringUtil.isEmpty(sno, 9) && !StringUtil.isEmpty(password, 6)) {
                        dialog.dismiss();
                        EventBus.getDefault().post(new MessageEvent("newStudent", 6, null));
                        JSONObject jsonObject = xxmhApi.login(sno, password, remberMe);
                        if (StringUtil.checkResult(jsonObject)) {
                            EventBus.getDefault().post(new MessageEvent("newStudent", 1, null));
                            SharedPreferencesUtil.putStringSp(this, "password_XXMH", password);
                            SharedPreferencesUtil.putStringSp(this, "stuNum", sno);
                            JSONObject object = jsonObject.getJSONObject("info");
                            cookies = JSONObject.parseObject(object.toJSONString(), new TypeReference<Map<String, String>>() {
                            });
                        } else if (jsonObject != null && jsonObject.containsKey("resultMsg") && jsonObject.getString("resultMsg").equals("异常")) {
                            EventBus.getDefault().post(new MessageEvent("newStudent", 10, 300000, "信息门户"));
                        } else
                            EventBus.getDefault().post(new MessageEvent("newStudent", 2, jsonObject.getString("resultMsg")));
                    } else EventBus.getDefault().post(new MessageEvent("newStudent", 8));
                });
            });
        });

    }

    public void jwxtLogin() {
        jwxt = findViewById(R.id.bind_jwxt);
        jwxt.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                if (bind) return;
                String stuNum = SharedPreferencesUtil.getStringSp(newStudent.this, "stuNum", null);
                String xxmh = SharedPreferencesUtil.getStringSp(newStudent.this, "password_XXMH", null);
                if (!xxmhLogined || StringUtil.isEmpty(stuNum, xxmh) || StringUtil.isEmpty(cookies) || cookies.size() < 3)
                    ToastUtil.showToast("🔊请先完成信息门户账号绑定");
                else {
                    threadPool.execute(() -> {
                        EventBus.getDefault().post(new MessageEvent("newStudent", 7, null));
                        JSONObject jsonObject = xxmhApi.jwxt(cookies);
                        if (Result.jsonResultIsTure(jsonObject)) {
                            EventBus.getDefault().post(new MessageEvent("newStudent", 3, null));
                            CookiesUtil.save(newStudent.this, cookies);
                            getInfo();
                            getCourse();
                        } else if (jsonObject != null && jsonObject.containsKey("resultMsg") && jsonObject.getString("resultMsg").equals("异常")) {
                            EventBus.getDefault().post(new MessageEvent("newStudent", 10, "教务系统"));
                        } else
                            EventBus.getDefault().post(new MessageEvent("newStudent", 4, jsonObject.getString("resultMsg")));

                    });
                }

            }

        });


//                DialogView.loginDialog(this, "教务系统", (dialog, userid, pwd, checkBox) -> {
//                    threadPool.execute(() -> {
//                        String remberMe = "0";
//                        if (checkBox.isChecked()) remberMe = "1";
//                        String sno = StringUtil.rmBadParame(userid.getText().toString());
//                        String password = StringUtil.rmBadParame(pwd.getText().toString());
//                        if (!StringUtil.isEmpty(sno, 9) && !StringUtil.isEmpty(password, 6)) {
//                            dialog.dismiss();
//                            EventBus.getDefault().post(new MessageEvent("newStudent", 7, null));
//                            EventBus.getDefault().post(new MessageEvent("newStudent", 5, userid));
//                            if (stuNum.equals(sno)) {
//                                JSONObject jsonObject = jwxtApi.login(cookies, sno, password, remberMe);
//                                if (StringUtil.checkResult(jsonObject)) {
//                                    EventBus.getDefault().post(new MessageEvent("newStudent", 3, null));
//                                    SharedPreferencesUtil.putStringSp(this, "password_JWXT", password);
//                                    CookiesUtil.save(this, cookies);
//                                    getInfo();
//                                } else if (jsonObject != null && jsonObject.containsKey("resultMsg") && jsonObject.getString("resultMsg").equals("异常")) {
//                                    EventBus.getDefault().post(new MessageEvent("newStudent", 10, "教务系统"));
//                                } else
//                                    EventBus.getDefault().post(new MessageEvent("newStudent", 4, jsonObject.getString("resultMsg")));
//                            } else EventBus.getDefault().post(new MessageEvent("newStudent", 9));
//                        } else EventBus.getDefault().post(new MessageEvent("newStudent", 8));
//                    });
//                });


    }

    public void getInfo() {
        threadPool.execute(() -> {
            String sno = SharedPreferencesUtil.getStringSp(this, "stuNum", null);
            JSONObject jsonObject = jwxtApi.info(sno, cookies);
            if (Result.jsonResultIsTure(jsonObject)) {
                if (jsonObject.containsKey("academic")) {
                    JSONObject object = jsonObject.getJSONObject("academic");
                    academic academic = object.toJavaObject(academic.class);
                    if (academic != null) {
                        MyApplication.getDaoInstant().getAcademicDao().deleteAll();
                        MyApplication.getDaoInstant().getAcademicDao().insertOrReplace(academic);
                    }
                }
                if (jsonObject.containsKey("info")) {
                    JSONObject object = jsonObject.getJSONObject("info");
                    student student = new student();
                    student.setXh(object.getString("sno"));
                    student.setXm(object.getString("name"));
                    student.setXy(object.getString("faculty"));
                    student.setZy(object.getString("specialities"));
                    student.setRxnf(object.getString("grade"));
                    student.setSf(object.getString("province"));
                    MyApplication.getDaoInstant().getStudentDao().insertOrReplace(student);

                }
                if (jsonObject.containsKey("head")) {
                    avatar avatar = new avatar();
                    avatar.setBytes(jsonObject.getBytes("head"));
                    MyApplication.getDaoInstant().getAvatarDao().deleteAll();
                    if (avatar.getBytes() != null)
                        MyApplication.getDaoInstant().getAvatarDao().insertOrReplace(avatar);
                }
                EventBus.getDefault().post(new MessageEvent("JWXT_main", 10, null));
            }
        });
    }


    public void getCourse() {
        threadPool.execute(() -> {
            String sno = SharedPreferencesUtil.getStringSp(this, "stuNum", null);
            int year, term, month;
            month = GetTimeUtil.getMonth();
            if (month > 6 || month < 2) {
                term = 1;
                year = GetTimeUtil.getYear();
            } else {
                term = 2;
                year = GetTimeUtil.getYear() - 1;
            }
            JSONObject jsonObject = jwxtApi.course(sno, year, term, cookies);
            if (Result.jsonResultIsTure(jsonObject)) {
                EventBus.getDefault().post(new MessageEvent("SubjectFragment", true));
            }
        });
    }

    public void jump() {
        Button button = findViewById(R.id.go);
        button.setOnClickListener(v -> {
            EasyPermissions.requestPermissions(this, "请授权以下权限:\n访问日历：设置上课提醒日程\n读写手机存储：自定义背景和头像等功能", 1, permissions);
            String xxmh = SharedPreferencesUtil.getStringSp(this, "password_XXMH", null);
            String sno = SharedPreferencesUtil.getStringSp(this, "stuNum", null);
//            String jwxt = SharedPreferencesUtil.getStringSp(this, "password_JWXT", null);
            if (xxmh != null && sno != null && sno.length() == 9 && bindJwxt) {
                Intent intent = new Intent(this, MainActivity.class);
                startActivity(intent);
                finish();
            } else ToastUtil.showToast("请完成账号绑定！");

        });

    }

    public void showYs() {
        AlertDialog alertDialog = new AlertDialog(this);
        alertDialog.builder();
        alertDialog.setGone()
                .setTitle("隐私协议和用户协议")
                .setMsg("感谢下载使用本应用，本应用由董琴平发布到应用市场，我们非常重视用户的隐私保护，本应用在任何未经允许的情况下收集您的任何隐私内容。强烈建议您认真阅读本文。\n" +
                        "《隐私政策》\n" +
                        "我们收集的数据\n" +
                        "1. 在您登录的过程中的主动授权云同步账号和密码的情况下我们将加密保存您的账号和密码到本应用数据库，账号仅用于数据的获取处理，已提供用户端更好的体验，同样防止相关数据丢失，所有数据均不会用以其他行为。\n" +
                        "2. 在您登录和获取过程中所产生的部分数据，我们都将会保存至服务器，以便用户下次获取，所有数据均不会用以其他行为。\n" +
                        "《用户协议》\n" +
                        "本应用仅用于辅助学生学习生活，本应用尽可能的提供相关明确提示帮助用户使用该产品，一切用户疏忽导致的相关后果均由用户自行承担。其中包括不限于：生成的课程表存在缺课或安排不一致错误，考场信息错误，等。")
                .setMsgGravity(false)
                .setCancelable(false)
                .setNegativeButton("我同意", R.color.colorAccent, v1 -> {
                    alertDialog.dismiss();
                    waitLimit();
                    xxmhLogin();
                    jwxtLogin();
                    jump();
                })
                .setPositiveButton("我拒绝", R.color.colorAccent, v2 -> {
                    alertDialog.dismiss();
                    finish();
                    System.exit(0);
                })
                .show();
    }


    public void waitLimit() {
        long limit_time = SharedPreferencesUtil.getLongSp(this, "limit_time", 0);
        if (limit_time != 0) {
            long now = Calendar.getInstance().getTimeInMillis();
            long x = now - limit_time;
            if (x < 5 * 60 * 1000) {
                EventBus.getDefault().post(new MessageEvent("newStudent", 10, (int) x, "信息门户"));
                loginError = 0;
            }
        }
    }


    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event.getEvent().equals("newStudent")) {
            switch (event.getWhat()) {
                case 1:
                    loginError = 0;
                    bind = false;
                    xxmhLogined = true;
                    viewstub_loading.setVisibility(View.GONE);
                    xxmh.setText("🏆绑定成功");
                    break;
                case 2:
                    loginError++;
                    bind = false;
                    xxmhLogined = false;
                    viewstub_loading.setVisibility(View.GONE);
                    if (StringUtil.isEmpty(event.getMessage(), 2))
                        event.setMessage("登录失败");
                    xxmh.setText("🤦" + event.getMessage());
                    break;
                case 3:
                    loginError = 0;
                    bind = false;
                    bindJwxt = true;
                    viewstub_loading1.setVisibility(View.GONE);
                    jwxt.setText("🏆绑定成功");
                    break;
                case 4:
                    loginError++;
                    bind = false;
                    viewstub_loading1.setVisibility(View.GONE);
                    if (StringUtil.isEmpty(event.getMessage(), 2))
                        event.setMessage("登录失败");
                    jwxt.setText("🤦" + event.getMessage());
                    break;
                case 5:
                    EditText userid = (EditText) event.getObj();
                    String stuNum = SharedPreferencesUtil.getStringSp(this, "stuNum", "");
                    userid.setText(stuNum);
                    break;
                case 6:
                    bind = true;
                    viewstub_loading.setVisibility(View.VISIBLE);
                    break;
                case 7:
                    bind = true;
                    viewstub_loading1.setVisibility(View.VISIBLE);
                    break;
                case 8:
                    ToastUtil.showToast("😒学号等于9位，密码长度大于6位");
                    break;
                case 9:
                    ToastUtil.showToast("两个账号学号必须相同");
                    break;
                case 10:
                    String web = "", help = "";
                    SharedPreferencesUtil.putLongSp(this, "limit_time", Calendar.getInstance().getTimeInMillis());
                    if (event.getMessage() == null) break;
                    if (event.getMessage().equals("信息门户")) {
                        web = "https://webvpn.cslg.edu.cn";
                        help = xxmhHelp;
                    }
                    if (event.getMessage().equals("教务系统")) {
                        web = "http://jwxt.cslg.edu.cn/jwglxt/（需要内网访问）";
                        help = "联系班主任进行更改重置";
                    }
                    AlertDialog alertDialog = new AlertDialog(this);
                    alertDialog.builder();
                    alertDialog.setGone()
                            .setTitle("登录提示")
                            .setMsg("您【" + event.getMessage() + "】登录失败次数已达上限，您的账号将被限制5分钟无法登录，请确认您的密码后再进行登录，请在5分钟后再进行登录操作！\n" +
                                    event.getMessage() + "【系统官网】：" + web + "\n" +
                                    event.getMessage() + "【密码重置】：" + help)
                            .setMsgGravity(false)
                            .setCancelable(false)
                            .setNegativeButtonCountDown(R.color.red, event.getZhou(), 1000, true, null)
                            .show();
                    loginError = 0;
                    break;
            }
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


}
